var HelloWorld = {
  onLoad: function() {
    // initialization code
    this.initialized = true;
  },
  onMenuItemCommand: function() {
    window.open("chrome://quickgooglecal/content/hello.xul", "",
    "modal,chrome,dependant,centerscreen,titlebar=no,statusbar=no");
  },
};

window.addEventListener("load", function() { QuickGoogleCalExtension.init(); }, false);

var QuickGoogleCalExtension = {
  init: function() {
    this.calendarList = [];
    this.feedsLoaded = false;
    this.feedsLoading = false;
  },
  
  loadFeeds: function(callback) {
    if(this.feedsLoading)
      return;
    this.calendarList = [];
    this.feedsLoading = true;
    this.feedsLoaded = false;

    var feed = "http://www.google.com/calendar/feeds/default/allcalendars/full";
    
    var req = new XMLHttpRequest();
    req.onreadystatechange = function() {
      if(req.readyState == 4) {
        if(req.getResponseHeader('Content-type').indexOf("text/xml") == -1) {
          this.feedsLoading = false;
          return; // User is not logged in, will try again when quick add is used
        }

        var xml = req.responseXML.documentElement;
        var entries = xml.getElementsByTagName('entry');	

        for (i = 0; i < entries.length; i++)
        {
          var ownershipNode = entries[i].getElementsByTagNameNS("http://schemas.google.com/gCal/2005", "accesslevel");      
          var ownership = ownershipNode.item(0).getAttribute("value");
          if(ownership != "owner" && ownership != "contributor")
            continue; // Read-only calendar, skip it
    		
          var hiddenNode = entries[i].getElementsByTagNameNS("http://schemas.google.com/gCal/2005", "hidden");      
          var hidden = hiddenNode.item(0).getAttribute("value");
          if(hidden == "true")
            continue; // Hidden calendar, skip it
            
          var x = entries[i].getElementsByTagName('link');
          for (j = 0; j < x.length; j++)
          {
            if(x[j].getAttribute('rel') == "alternate") // From what I've seen, this has the right feed URI
            {
              var entryName = entries[i].getElementsByTagName('title')[0].childNodes[0].nodeValue;
              QuickGoogleCalExtension.calendarList.push({ "name" : entryName, "href" : x[j].getAttribute('href') });
            }
          }
        }
        QuickGoogleCalExtension.feedsLoaded = true;
        QuickGoogleCalExtension.feedsLoading = false;
        if(callback) 
          callback.apply();
      }
    };
    req.open('GET', feed, true);
    req.send(null);
  }

}

window.addEventListener("load", function(e) { HelloWorld.onLoad(e); }, false); 

function reloadCalendar() {
  try {
    var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator);
    var enumerator = wm.getEnumerator("navigator:browser");
    while(enumerator.hasMoreElements()) {
      var win = enumerator.getNext();
      var index = 0, numTabs = win.getBrowser().mPanelContainer.childNodes.length;
      while (index < numTabs) {
      	var currentTab = win.getBrowser().getBrowserAtIndex(index);
      	if(currentTab.currentURI.spec.indexOf("google.com/calendar") > -1) {
      	  currentTab.reload();
      	}
      	index++;
      }
    }
  } catch(e) {
    alert("error" + e);
  }
}


window.addEventListener("load", function() { calendarDecryptExtension.init(); }, false);

var calendarDecryptExtension = {
  init: function() {
    var appcontent = document.getElementById("appcontent");   // browser
    if(appcontent)
      appcontent.addEventListener("DOMContentLoaded", this.onPageLoad, true);
    var messagepane = document.getElementById("messagepane"); // mail
    if(messagepane)
      messagepane.addEventListener("load", function () { calendarDecryptExtension.onPageLoad(); }, false);
  },
  onPageLoad: function(aEvent) {
    dump("pre elemenet \n");
   
    var elementData = "NODATA";
    var allSpans = content.document.getElementsByTagName("span");

    for (var n = 0; n < allSpans.length; n++){
      if( allSpans[n].innerHTML.indexOf("BEGIN PGP") > -1 ){

        // file output for encrypted event text
        elementData = allSpans[n].innerHTML;
        var fileOut = Components.classes["@mozilla.org/file/local;1"]
                        .createInstance(Components.interfaces.nsILocalFile);
        fileOut.initWithPath("/tmp/calendarEvent.temp");
        var foStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
                                .createInstance(Components.interfaces.nsIFileOutputStream);
        foStream.init(fileOut, 0x02 | 0x08 | 0x20, 0666, 0);
        foStream.write(elementData, elementData.length);
        foStream.close();
      
        // create an nsILocalFile for the executable
        var fileExe = Components.classes["@mozilla.org/file/local;1"]
                            .createInstance(Components.interfaces.nsILocalFile);
        fileExe.initWithPath("/tmp/CalendarCrypt.pl"); 
        var process = Components.classes["@mozilla.org/process/util;1"]
                                .createInstance(Components.interfaces.nsIProcess);
        process.init(fileExe);
        var args = ["decrypt"];
        process.run(true, args, args.length);
        // file input for decrypted event text
        var data = "";
        var fileIn = Components.classes["@mozilla.org/file/local;1"]
                            .createInstance(Components.interfaces.nsILocalFile);
        fileIn.initWithPath("/tmp/calendarEvent.decrypted");
        var istream = Components.classes["@mozilla.org/network/file-input-stream;1"]
                                .createInstance(Components.interfaces.nsIFileInputStream);
        istream.init(fileIn, 0x01, 0444, 0);
        istream.QueryInterface(Components.interfaces.nsILineInputStream);
        var fstream = Components.classes["@mozilla.org/network/file-input-stream;1"]
                                .createInstance(Components.interfaces.nsIFileInputStream);
        var sstream = Components.classes["@mozilla.org/scriptableinputstream;1"]
                                .createInstance(Components.interfaces.nsIScriptableInputStream);
        fstream.init(fileIn, -1, 0, 0);
        sstream.init(fstream);

        var str = sstream.read(4096);
        while (str.length > 0) {
          data += str;
          str = sstream.read(4096);
        }

        sstream.close();
        fstream.close();

        allSpans[n].innerHTML = data;

        // sanitize the data stored on disk
        args = ["shred"]; 
        process.run(true, args, args.length);
      
      }//if the span item is encrypted
    
    }//for each span
  
  }//on page load
}//calendarDecryptExtension
